{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "496bf1d5",
   "metadata": {},
   "source": [
    "# 自定义优化器\n",
    "在训练神经网络过程中，我们使用优化器来计算和更新参数。与其他自定义类似，自定义优化器时需继承一个基类，这里是`nn.Optimizer`，依旧需要重写`__init__`方法和`construct`方法实现参数的更新。在`__init__`方法中定义需要用到的算子，在`construct`方法中实现参数计算与更新。我们以优化器Momentum（带动量的SGD算法）举例：\n",
    "\n",
    "$$ v_{t+1} = v_t × u+grad $$\n",
    "\n",
    "$$p_{t+1} = p_t - lr × v_{t+1} $$\n",
    "\n",
    "- $grad$：梯度\n",
    "- $lr$：学习率\n",
    "- $p$：权重参数\n",
    "- $v$：动量参数\n",
    "- $u$：初始速度"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "b0f090ae",
   "metadata": {},
   "outputs": [],
   "source": [
    "import mindspore as ms\n",
    "import mindspore.nn as nn\n",
    "import mindspore.ops as ops\n",
    "\n",
    "class MyOptimizer(nn.Optimizer):\n",
    "    \"\"\"自定义优化器\"\"\"\n",
    "    def __init__(self, learning_rate, params, momentum=0.9):\n",
    "        super(MyOptimizer, self).__init__(learning_rate, params)\n",
    "        self.assign = ops.Assign()\n",
    "        # 定义初速度\n",
    "        self.moment = ms.Parameter(ms.Tensor(momentum, ms.float32), name=\"moment\")\n",
    "        # 定义动量参数\n",
    "        self.momentum = self.parameters.clone(prefix=\"momentum\", init=\"zeros\")\n",
    "        \n",
    "    def construct(self, gradients):\n",
    "        lr = self.get_lr()\n",
    "        params = self.parameters\n",
    "        for i in range(len(params)):\n",
    "            # 给网络赋值动量参数\n",
    "            self.assign(self.momentum[i], self.momentum[i] * self.moment + gradients[i])\n",
    "            # 计算新的权重参数\n",
    "            update = params[i] - self.momentum[i] * lr\n",
    "            # 更新权重参数\n",
    "            self.assign(params[i], update)\n",
    "        return params"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "001d2f52",
   "metadata": {},
   "source": [
    "继承`nn.Optimizer`自定义优化器时，可在参数更新前调用`get_lr()`获取学习率。\n",
    "\n",
    "`ops`中的`Assign()`算子可以为网络模型赋值，其有两个参数，第一个参数为赋值对象，第二个参数为所赋的值。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "mindspore",
   "language": "python",
   "name": "mindvision"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
